const Components = require("../models/components");

class ComponentsCtl {
  async get(ctx) {
    let limit = ctx.query.limit ? ctx.query.limit : 10;
    let page = ctx.query.page ? ctx.query.page : 1;

    let where = {};
    const filters = ["name"];
    filters.forEach((key) => {
      if (ctx.query[key]) {
        if (key === "name") {
          where[key] = new RegExp(ctx.query[key]);
        } else {
          where[key] = ctx.query[key];
        }
      }
    });

    let _Components = await Components.find(where);
    limit = parseInt(limit);
    let skip = limit * (parseInt(page) - 1);
    let total = _Components.length;
    let list = [];

    if (total > 0) {
      list = await Components.find(where)
        .limit(limit)
        .skip(skip)
        .sort({ _id: -1 });
    }

    ctx.body = {
      code: 200,
      msg: "success",
      data: {
        limit: limit,
        page: page,
        list: list,
        total: total,
      },
    };
  }

  async all(ctx) {
    let _Components = await Components.find({});
    ctx.body = {
      code: 200,
      msg: "success",
      data: _Components,
    };
  }

  async create(ctx) {
    const name = ctx.request.body.name;
    const code = ctx.request.body.code;
    const content = ctx.request.body.content;
    const exit = await Components.findOne({
      $or: [{ name: name }, { code: code }],
    });
    if (exit) {
      ctx.body = {
        errCode: -1,
        msg: "组件已存在",
      };
      return;
    }

    const _Components = await new Components({
      name,
      code,
      content,
      createAt: new Date(),
      updateAt: new Date(),
    }).save();

    ctx.body = {
      code: 200,
      msg: "success",
      data: _Components,
    };
  }

  async modify(ctx) {
    const _id = ctx.request.body._id;
    const name = ctx.request.body.name;
    const code = ctx.request.body.code;
    const content = ctx.request.body.content;
    const exit = await Components.findOne({
      $or: [{ code: code }, { name: name }],
      _id: { $ne: _id },
    });
    if (exit) {
      ctx.body = {
        code: -1,
        msg: "组件已存在",
      };
      return;
    }
    console.log(name, code, "sdsds");
    const _Components = await Components.updateOne(
      { _id: _id },
      {
        name,
        code,
        content,
        updateAt: new Date(),
      }
    );

    ctx.body = {
      code: 200,
      msg: "success",
      data: _Components,
    };
  }

  async remove(ctx) {
    const id = ctx.params.id;
    await Components.remove({
      _id: id,
    });

    ctx.body = {
      code: 200,
      msg: "success",
    };
  }
}

module.exports = new ComponentsCtl();
